package cn.cjlmonster.demo02.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import cn.cjlmonster.demo02.R;

/**
 * This project is Demo02
 * Created by cjl on 2021/11/7 5:35 下午.
 */

public class MainAdapter extends RecyclerView.Adapter<MainAdapter.Holder> {

    private final LayoutInflater inflater;
    private final String[] mData;
    private final OnItemClickedListener listener;

    public MainAdapter(Context context, String[] mData, OnItemClickedListener listener) {
        this.inflater = LayoutInflater.from(context);
        this.mData = mData;
        this.listener = listener;
    }

    @NonNull
    @Override
    public Holder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = inflater.inflate(R.layout.item_main, parent, false);
        return new Holder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull Holder holder, int position) {
        holder.tv_demo.setText(mData[position]);
        holder.itemView.setOnClickListener(v-> listener.onItemClicked(position, mData[position]));
    }

    @Override
    public int getItemCount() {
        return mData.length;
    }

    static class Holder extends RecyclerView.ViewHolder {

        TextView tv_demo;

        public Holder(@NonNull View itemView) {
            super(itemView);
            tv_demo = itemView.findViewById(R.id.tv_demo);
        }
    }

    public interface OnItemClickedListener {
        void onItemClicked(int position, String item);
    }
}
